package cn.yunhe.zhuxing;

import cn.yunhe.bean.News;
import org.jfree.chart.ChartFactory;

import org.jfree.chart.ChartPanel;

import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;

import org.jfree.chart.axis.CategoryAxis;

import org.jfree.chart.axis.ValueAxis;

import org.jfree.chart.plot.CategoryPlot;

import org.jfree.chart.plot.PlotOrientation;

import org.jfree.data.category.CategoryDataset;

import org.jfree.data.category.DefaultCategoryDataset;

import javax.swing.*;

import java.awt.*;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.sql.*;

import java.util.ArrayList;
import java.util.List;

/**

 * 测试柱状图

 * Created by shaowei on 2017/8/16.

 */

public class Testdemo {

    ChartPanel frame;

    public Testdemo() {

        CategoryDataset dataset = getDataSet();

        JFreeChart chart = ChartFactory.createBarChart3D(

                "新闻", // 图表标题

                "新闻标题", // 目录轴的显示标签

                "id", // 数值轴的显示标签

                dataset, // 数据集

                PlotOrientation.VERTICAL, // 图表方向：水平、垂直

                true,      // 是否显示图例(对于简单的柱状图必须是false)

                false,     // 是否生成工具

                false      // 是否生成URL链接

        );

        //从这里开始

        CategoryPlot plot = chart.getCategoryPlot();//获取图表区域对象

        CategoryAxis domainAxis = plot.getDomainAxis();     //水平底部列表

        domainAxis.setTickLabelFont(new Font("宋体", Font.BOLD, 12)); //垂直标题

        domainAxis.setLabelFont(new Font("黑体", Font.BOLD, 14));     //水平底部标题

        ValueAxis rangeAxis = plot.getRangeAxis();//获取柱状

        rangeAxis.setLabelFont(new Font("黑体", Font.BOLD, 15));

        chart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 15));

        chart.getTitle().setFont(new Font("宋体", Font.BOLD, 20));//设置标题字体

        //到这里结束，虽然代码有点多，但只为一个目的，解决汉字乱码问题

        frame = new ChartPanel(chart, true);    //这里也可以用chartFrame,可以直接生成一个独立的Frame




    }

    private static CategoryDataset getDataSet() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        News news1 = new News(1,"nihao","我是一个好人");
        News news2 = new News(1,"军事","军事厉害牛");
        News news3 = new News(1,"体育","体育锻炼身体");

        List<News> newsList = new ArrayList<>();
        newsList.add(news1);
        newsList.add(news2);
        newsList.add(news3);

        for (News news : newsList) {

            dataset.addValue(news.getNewId(),news.getTitle(),news.getContect());

        }

        return dataset;

    }

    public ChartPanel getChartPanel() {

        return frame;

    }



    public static void main(String[] args) {

        JFrame frame = new JFrame("Java柱状图图");


        frame.add(new Testdemo().getChartPanel()); // 添加柱形图

        frame.setBounds(50, 50, 800, 600);

        frame.setVisible(true);


    }
}